# Concave
# Copyright (C) 2012 Daniel Malmqvist
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


import g
import constants
import random
import pygame
import os
from item import Item
import helperfunctions


class NPC():
    def __init__(self, npcId):
        self.npcId = npcId
        self.dialogImage = [0]
        self.talking = False
        
        f = open(os.path.join("npc", str(npcId) + ".npc"), "r")
        
        coord = f.readline().split(",")
        self.x = int(coord[0])
        self.y = int(coord[1])
        self.name = f.readline().split("\n")[0]
        self.type = int(f.readline())
        self.level = 1
        
        lines = int(f.readline())
        self.text = []
        
        while lines > 0:
            self.text.append(f.readline().split("\n")[0])
            lines -= 1
        
        buttons = int(f.readline())
        self.buttons = []
        while buttons > 0:
            self.buttons.append(f.readline().split("\n"))
            buttons -= 1
        
        self.itemsForSale = []
        
        if self.type == constants.MERCHANT():
            items = int(f.readline())
            self.level = g.getPlayer().level
            while items > 0:
                levelPoints = g.getPlayer().level + random.randint(0,self.level*5)
                levelPoints = random.randint(0, max(levelPoints, 1))
                itemProp = f.readline().split("\n")[0].split(",")
                apa = Item(-1, -1, int(itemProp[0]), int(itemProp[1]), levelPoints)
                apa.generateName()
                self.itemsForSale.append(apa)
                items -= 1
        
    def talk(self):
        # Update items if player has reached a new level
        if self.type == constants.MERCHANT() and self.level < g.getPlayer().level:
            newItems = []
            self.level = g.getPlayer().level
            for i in range(0,len(self.itemsForSale)):
                levelPoints = g.getPlayer().level + random.randint(0,self.level*5)
                newItems.append(Item(-1, -1, self.itemsForSale[i].type, self.itemsForSale[i].level, levelPoints))
            
            self.itemsForSale = newItems
                
        self.talking = True
        
    def getImage(self, direction = constants.SOUTH()):
        return g.getNPCImage(self.npcId, direction)
    
    def getHitRect(self):
        return pygame.rect.Rect(self.x+8, self.y+48, 16,32)
    
    def getUseRect(self):
        return pygame.rect.Rect(self.x-16, self.y, 112, 128)
    
    def getDialogImage(self, pageId = 0):
        if self.dialogImage[pageId] == 0:
            textPortion = helperfunctions.renderLines(self.text, g.fontNormal, 1, (255,255,255))
            height = textPortion.get_height()
            if len(self.itemsForSale) > 0:
                height += 92 # item box(64) + a little space
            
            height += 48 # Bye/next box(32) + a little space
        
            width = max(textPortion.get_width(), 160)
            
            rect = pygame.Rect((0,0, width, height))
            self.dialogImage[0] = pygame.Surface(rect.size, pygame.locals.SRCALPHA)
            
            self.dialogImage[0].blit(textPortion, (0,0))
            npcBye = pygame.image.load(os.path.join("graphic","npcbye.png"))
            if len(self.itemsForSale) > 0:
                npcItemGrid = pygame.image.load(os.path.join("graphic","npcitemgrid.png"))
                self.dialogImage[0].blit(npcItemGrid, (0,textPortion.get_height()+16))
                
                (self.itemStartX, self.itemStartY) = (0, textPortion.get_height()+16)
                
                for i in range(0,len(self.itemsForSale)):
                    self.dialogImage[0].blit(g.getItemImages()[(self.itemsForSale[i].type, self.itemsForSale[i].level)], (self.itemStartX+(i%5)*32, self.itemStartY+((i)/5)*32))
                    
                
                
                self.dialogImage[0].blit(npcBye, (width - 64, textPortion.get_height()+100))
                (self.buttonStartX, self.buttonStartY) = (width - 64, textPortion.get_height()+100)
            else:
                self.dialogImage[0].blit(npcBye, (width - 64, textPortion.get_height()+8))
                (self.buttonStartX, self.buttonStartY) = (width - 64, textPortion.get_height()+8)
            
        return self.dialogImage[0]
    
    def onClick(self, x, y):
        if x >= self.buttonStartX and x <= self.buttonStartX + 64 and y >= self.buttonStartY and y <= self.buttonStartY + 32:
            self.talking = False
        if len (self.itemsForSale) > 0:
            if x >= self.itemStartX and x <= self.itemStartX + 160:
                if y >= self.itemStartY and y <= self.itemStartY + 64:
                    x -= self.itemStartX
                    y -= self.itemStartY
                    x = x/32
                    y = y/32
                    if x >= 0 and x <= 4 and y >= 0 and y <= 4:
                        
                        if (len(self.itemsForSale)) > (x+5*y):
                            return self.itemsForSale[x+5*y]
                     